package com.warm.androidstudy.utils;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.text.TextUtils;


import com.warm.androidstudy.MyApplication;
import com.warm.androidstudy.config.AppConfig;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;


/**
 * App文件管理类
 * 所有文件操作进出都有这里执行
 * by admin on 2016/1/18
 */
public class FileManager {

    private static FileManager instance;
    public static String rootDirectoryPath;//文件存储根路径（例如sd卡：storage/sdcard0/zysoft/IJHealth）

    public static FileManager getInstance() {
        if (instance == null) {
            instance = new FileManager();
        }
        return instance;
    }

    /**
     * 初始化默认文件存放路径
     */
    private void initRootDirectoryPath() {
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {//有可用的SK卡
            rootDirectoryPath = Environment.getExternalStorageDirectory().getPath();
        } else { //取内置缓存目录
            rootDirectoryPath = MyApplication.getInstance().getCacheDir().getPath();
        }
    }

    public FileManager() {
        initRootDirectoryPath();
    }

   /* public String getDiskCacheDir(Context context) {
        String cachePath = null;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            cachePath = context.getExternalCacheDir().getPath();
        } else {
            cachePath = context.getCacheDir().getPath();
        }
        return cachePath;
    }

    *//*
    public  String getDiskFileDir(Context context) {
        String filePath = null;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            filePath = context.getExternalFilesDir(null).getPath();
        } else {
            filePath = context.getFilesDir().getPath();
        }
        return filePath;
    }*/

    private String getArrayDir(String[] pathNameArr) {
        String pathName = rootDirectoryPath;
        for (int i = 0; i < pathNameArr.length; i++) {
            pathName += pathNameArr[i];
            File dirFirstFile = new File(pathName);// 新建一级主目录
            if (!dirFirstFile.exists()) {// 判断文件夹目录是否存在
                dirFirstFile.mkdir();// 如果不存在则创建
            }
        }
        return pathName + File.separator;
    }

    /**
     * 获取储存Image的目录
     *
     * @return
     */
    public String getStorageImageDirectory() {
        return getArrayDir(AppConfig.IMAGE_FILE_FOLDER);
    }

    /**
     * 获取储存DownLoad的目录
     *
     * @return
     */
    public String getStorageDownLoadDirectory() {
        return getArrayDir(AppConfig.DOWNLOAD_FILE_FOLDER);
    }

    /**
     * 保存Image的方法，有sd卡存储到sd卡，没有就存储到手机目录
     *
     * @param fileName
     * @param bitmap
     * @throws IOException

    public String savaBitmap(String fullFileName) throws IOException {
    if (fullFileName == null) return null;

    String path = getStorageImageDirectory();
    //文件存在,删除
    File file = new File(path + File.separator + fileName);
    if (file.isFile() && file.exists()) {
    file.delete();
    }

    //文件夹不存在，创建
    File folderFile = new File(path);
    if (!folderFile.exists()) {
    folderFile.mkdir();
    }
    File fileNew = new File(path + File.separator + fileName);
    FileOutputStream fos = new FileOutputStream(fileNew);
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
    fos.flush();
    fos.close();
    return path + File.separator + fileName;
    }
     */
    /**
     * 从手机或者sd卡获取Bitmap
     *
     * @param fullPathFile
     * @return
     */
    public Bitmap getBitmap(String fullPathFile) {
        return BitmapFactory.decodeFile(fullPathFile);
    }


    /**
     * 文件夹不存在，创建
     *
     * @param directoryPath
     */
    public void createFileIfNoExist(String directoryPath) {
        File folderFile = new File(directoryPath);
        if (!folderFile.exists()) {
            folderFile.mkdir();
        }
    }

    /**
     * 获取文件的大小
     *
     * @param fileName
     * @return
     */
    public long getFileSize(String fileName) {
        return new File(getStorageImageDirectory() + File.separator + fileName).length();
    }


    /**
     * 删除SD卡或者手机的目录
     */
    public void deleteDirectory(String directoryPath) {
        File dirFile = new File(directoryPath);
        if (!dirFile.exists()) {
            return;
        }
        if (dirFile.isDirectory()) {
            String[] children = dirFile.list();
            for (int i = 0; i < children.length; i++) {
                new File(dirFile, children[i]).delete();
            }
        }
        dirFile.delete();
    }

    /**
     * 递归删除
     */
    public void deleteFolder(File file) {
        if (!file.exists())
            return;
        if (file.isDirectory()) {
            File files[] = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                deleteFolder(files[i]);
            }
        }
        file.delete();
    }

    public void deleteAppDate(Activity activity) {
        //删除配置文件目录shared_prefs；
        //路径：/data/data/packagename
        String path = activity.getFilesDir().getParent();
        deleteFolder(new File(path + "/shared_prefs"));
        //清空缓存目录；
        //路径 /data/data/packagename/cache
        File file_cache = activity.getCacheDir();
        deleteFolder(file_cache);

        //清空file目录；
        //路径 /data/data/packagename/files
        File file_file = activity.getFilesDir();
        deleteFolder(file_file);
        //清空数据库目录；
        File file_db = new File(path + "/databases");
        deleteFolder(file_db);
    }

    /**
     * 删除文件
     *
     * @param fullPathFile
     */
    public void deleteFile(String fullPathFile) {
        if (TextUtils.isEmpty(fullPathFile)) return;
        //文件存在,删除
        File file = new File(fullPathFile);
        if (file.isFile() && file.exists()) {
            file.delete();
        }
    }


    /**
     * 判断文件是否存在
     *
     * @param strFile
     * @return
     */
    public static boolean isFileExists(String strFile) {
        try {
            File f = new File(strFile);
            if (!f.exists()) {
                return false;
            }
        } catch (Exception e) {
            return false;
        }

        return true;
    }

    /**
     * 复制单个文件
     *
     * @param oldPath String 原文件路径 如：c:/fqf.txt
     * @param newPath String 复制后路径 如：f:/fqf.txt
     * @return boolean
     */
    public static void copyFile(String oldPath, String newPath) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { //文件存在时
                InputStream inStream = new FileInputStream(oldPath); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小
                    System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        } catch (Exception e) {
            System.out.println("复制单个文件操作出错");
            e.printStackTrace();
        }
    }
}
